package com.cms.controller.operation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cms.bean.Interface;
import com.cms.bean.InterfaceParam;
import com.cms.common.JsonResult;
import com.cms.util.RecordUtil;
import com.cms.vo.InterfaceModuleVO;
import com.cms.vo.InterfaceSystemVO;
import com.cms.vo.InterfaceVO;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.BeanUtil;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;
import com.mock.base.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by lichengming on 2017/6/30.
 */
public class InterfaceController extends Controller {

    private static final Logger logger = LoggerFactory.getLogger(InterfaceController.class);

    public void list() {

        String sql = "select system_name from cms_interface group by system_name";//系统名--中铭志
        List<String> systemList = Db.query(sql);
        List<InterfaceSystemVO> interfaceSystemVOList = new ArrayList<>();
        systemList.forEach(systemName -> {
            InterfaceSystemVO interfaceSystemVO = new InterfaceSystemVO();
            interfaceSystemVO.setName(systemName);
            interfaceSystemVO.setSeek("intr_system" + new Random().nextLong());
            interfaceSystemVOList.add(interfaceSystemVO);

            String moduleSQL = "select module_name from cms_interface where system_name = ? group by module_name order by id asc ";
            List<String> moduleNameList = Db.query(moduleSQL,systemName);
            if (CollectionUtil.isEmpty(moduleNameList)) return;

            List<InterfaceModuleVO> interfaceModuleVOList = new ArrayList<>();
            moduleNameList.forEach(moduleName -> {
                InterfaceModuleVO interfaceModuleVO = new InterfaceModuleVO();
                interfaceModuleVO.setName(moduleName);
                interfaceModuleVO.setSeek("intr_module" + new Random().nextLong());
                interfaceSystemVO.setInterfaceModuleVOList(interfaceModuleVOList);
                interfaceModuleVOList.add(interfaceModuleVO);

                List<InterfaceVO> interfaceVOList = new ArrayList<>();
                //第三层
                String interfaceSQL = "select id,name,ret_json from cms_interface where module_name = ? and system_name = ? ";
                List<Record> recordList = Db.find(interfaceSQL,moduleName,systemName);
                if (CollectionUtil.isEmpty(recordList)) {
                    interfaceModuleVO.setInterfaceVOList(interfaceVOList);
                    return;
                }
                recordList.forEach(record -> {
                    InterfaceVO interfaceVO = new InterfaceVO();
                    interfaceVO.setId(record.getLong("id"));
                    interfaceVO.setName(record.get("name"));
                    interfaceVO.setRet_json(record.get("ret_json"));
                    interfaceVOList.add(interfaceVO);
                });
                interfaceModuleVO.setInterfaceVOList(interfaceVOList);
            });
        });
        setAttr("interfaceSystemVOList",interfaceSystemVOList);
        renderJsp("/pages/operation/interface_list.jsp");
    }

    public void info() {
        Long id = getParaToLong("id");
        if (null == id) {
            renderNull();
            return;
        }

        Record record = Db.findById("cms_interface",id);
        if (null == record) {
            renderNull();
            return;
        }

        //调用参数列表
        List<Record> paramList = Db.find("select * from cms_interface_param where interface_id = ? and type = 1 ",id);
        if (CollectionUtil.isNotEmpty(paramList)) {
            paramList.forEach(param -> {
                String isNeedStr = param.getInt("is_need") == 1 ? "<span class='p_need'>是</span>" : "否";
                param.set("is_need", isNeedStr);
            });
        }
        record.set("paramList",paramList);

        //返回值列表
        List<Record> returnParamList = Db.find("select * from cms_interface_param where interface_id = ? and type = 2 ",id);
        record.set("returnParamList",returnParamList);

        //添加服务器
        List<Record> serverList = Db.find("SELECT * FROM server_manage");

        setAttr("serverList",serverList);
        setAttr("info",record);
        renderJsp("/pages/operation/interface_info.jsp");
    }

    public void index() {
        renderJsp("/pages/operation/interface_manage_list.jsp");
    }

    public void pagination() {

        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        StringBuilder exceptSelectSQL = new StringBuilder(" from cms_interface where 1 = 1 ");
        List<Object> params = new ArrayList<Object> ();

        String name = getPara("name");
        if (StringUtil.isNotEmpty(name)) {
            exceptSelectSQL.append(" and name like ?");
            params.add("%" + name.trim() + "%");
        }

        String moduleName = getPara("moduleName");
        if (StringUtil.isNotEmpty(moduleName)) {
            exceptSelectSQL.append(" and module_name = ? ");
            params.add(moduleName);
        }

        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber,pageSize,"select * ",exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber,pageSize,"select * ",exceptSelectSQL.toString(),params.toArray());
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void add() {
        renderJsp("/page/operation/interface_add.jsp");
    }

    public void edit() {
        Long interfaceId = getParaToLong("id");
        Long systemId = getParaToLong("systemId");
        if (null != interfaceId) {
            Record interfaceRecord = Db.findById("cms_interface",interfaceId);
            List<Record> paramList = Db.find("select id,param_name,param_type,description,is_need,param_name_zh " +
                    " from cms_interface_param where interface_id = ? and type = 1",interfaceId);
            if (CollectionUtil.isEmpty(paramList)) {
                paramList = new ArrayList<>();
                paramList.add(RecordUtil.newInterfaceParamRecord());
            } else {
                paramList.forEach(item -> {item.set("isNeedName", UUIDUtil.generateUUID().substring(8));});
            }
            interfaceRecord.set("paramList",paramList);

            List<Record> returnParamList = Db.find("select id,param_name,param_type,description " +
                    "from cms_interface_param where interface_id = ? and type = 2 ",interfaceId);
            if (CollectionUtil.isEmpty(returnParamList)) {
                returnParamList = new ArrayList<>();
                returnParamList.add(RecordUtil.newInterfaceParamRecord());
            }
            interfaceRecord.set("returnParamList",returnParamList);
            setAttr("interfaceRecord",interfaceRecord);
        }else {
            //没有进入页面选择系统
                Record record = new Record();
                List<Record> paramList = new ArrayList<>();

                Record param = new Record();
                param.set("isNeedName", UUIDUtil.generateUUID());
                paramList.add(param);
                record.set("paramList", paramList);

                List<Record> returnParamList = new ArrayList<>();
                returnParamList.add(new Record());
                record.set("returnParamList", returnParamList);

                //级联设置
            List<Record> systems = Db.find("SELECT * FROM system_manage");

            setAttr("system",systems);
            setAttr("interfaceRecord", record);
        }
        renderJsp("/pages/operation/interface_add.jsp");
    }

    @Before(Tx.class)
    public void save() {

        String system_id = getPara("system_id");
        String module_id = getPara("module_id");

        Interface ainterface = getBean(Interface.class,"");

        if(system_id!=null&&module_id!=null){
            Record system = Db.findFirst("SELECT * FROM system_manage WHERE id = ?", system_id);
            ainterface.setSystem_name(system.getStr("system_name"));

            Record module = Db.findFirst("SELECT * FROM module_manage WHERE id = ?", module_id);
            ainterface.setModule_name(module.getStr("module_name"));
        }

        JsonResult result = new JsonResult();
        Record record = new Record();
        try {
            record.setColumns(BeanUtil.objectToMap(ainterface));
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            renderJson(result.status("-1").show("保存失败"));
            return;
        }

        boolean success;
        if (ainterface.getId() == null) {
            if (Db.findFirst("select id from cms_interface where url = ?",ainterface.getUrl()) != null) {
                renderJson(result.status("-2").show("接口已存在,不能重复添加"));
                return;
            }
            success = Db.save("cms_interface",record);
        }else {
            success = Db.update("cms_interface",record);
        }

        String paramList = getPara("param_list");
        String returnParamList = getPara("return_param_list");
        saveParams(paramList,returnParamList,record.getLong("id"));

        if (success) {
            renderJson(result.status("000").show("保存成功"));
        }else {
            renderJson(result.status("-3").show("保存失败"));
        }
    }

    public void delete() {

        String paramIdList = getPara("interfaceIdList");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(paramIdList)) {
            renderJson(result.status("001").show("删除失败"));
            return;
        }

        StringBuilder deleteSQL = new StringBuilder("delete from cms_interface where id in (");
        Object [] params = new Object[paramIdList.split(",").length];
        int index = 0;
        for (String id : paramIdList.split(",")) {
            deleteSQL.append("?,");
            params[index]= id;
            index ++;
        }
        deleteSQL.deleteCharAt(deleteSQL.length() - 1).append(")");
        boolean deleteResult = Db.update(deleteSQL.toString(),params) == params.length;
        renderJson(deleteResult ? result.status("000").show("删除成功"):result.status("002").show("删除失败"));
    }

    private boolean saveParams(String paramList,String returnParamList,Long interfaceId) {

        List<InterfaceParam> params = JSON.parseArray(paramList,InterfaceParam.class);
        params.addAll(JSON.parseArray(returnParamList,InterfaceParam.class));

        //删除原来的参数
        Db.update("delete from cms_interface_param where interface_id = ? ",interfaceId);

        if (CollectionUtil.isNotEmpty(params)) {
            params.stream().filter(inter -> StringUtil.isNotEmpty(inter.getParam_name()))
                    .forEach(anInterface -> {
                        anInterface.setInterface_id(interfaceId);
                        Record record = new Record();
                        try {
                            record.setColumns(BeanUtil.objectToMap(anInterface));
                        } catch (Exception e) {
                            logger.error(e.getMessage(),e);
                            return;
                        }
                        Db.save("cms_interface_param",record);
                    });
        }
        return true;
    }

    //二级联动获取模块数据
    public void getModuleNameList() {

        String systemId = getPara("systemId");

        List<Record> ModuleNameList = Db.find("SELECT * FROM module_manage WHERE system_id = ?", systemId);
        JSON.toJSONString(ModuleNameList);

        JsonResult result = new JsonResult();

        renderJson(result.data(ModuleNameList).status("000"));
    }
}
